<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card>
        <page-tools>
          <!-- 插入到left插槽位置 -->
          <template #left>
            <span>总计100条数据</span>
          </template>
          <!-- 插入到right插槽位置 -->
          <template #right>
            <el-button v-if="canClick('p-em-import')" type="primary" size="small" @click="$router.push('/import')">导入excel</el-button>
            <el-button
              v-if="canClick('p-em-export')"
              type="primary"
              size="small"
              :loading="downloadLoading"
              @click="exportData"
            >导出excel</el-button>
            <el-button v-if="canClick('p-em-add')" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
          </template>
        </page-tools>
      </el-card>
    </div>
    <div>
      <el-card>
        <!-- table列表 -->
        <el-table :data="list" border>
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template #default="{row}">
              <!-- <p>{{ row }}</p> -->
              <el-image class="round" :src="row.staffPhoto" @click="showCode(row.staffPhoto)"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column label="聘用形式">
            <!-- 1. 使用作用域插槽获取当前行数据 2. 格式化数据 -->
            <template #default="{ row }">{{ formatForm(row.formOfEmployment) }}</template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="correctionTime" label="入职时间" />
          <el-table-column label="账户状态">
            <el-switch v-model="qy" />
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${scope.row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="editRole(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDelEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            background
            :total="total"
            :page-sizes="[10,5]"
            :page-size="params.size"
            layout="prev, pager, next,sizes"
            @size-change="sizeChange"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
    </div>
    <AddEmployee :show-dialog="showDialog" @close-dialog="showDialog = $event" />
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-row type="flex" justify="center">
        <!-- canvas元素（画布）=》专门用来绘图 -->
        <canvas ref="qr" />
      </el-row>
    </el-dialog>
    <!-- 权限分配 -->
    <AssignRole ref="roleDialog" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumTypes from '@/api/constant/employees'
import AssignRole from './components/assign-role.vue'
import qrcode from 'qrcode'
// console.log(EnumTypes)
import AddEmployee from './components/add-employee.vue'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data () {
    return {
      qy: true,
      showDialog: false,
      downloadLoading: false,
      dialogVisible: false,
      // 分配权限
      showRoleDialog: false,
      list: [],
      total: 0,
      params: {
        page: 1,
        size: 10
      }
    }
  },
  created () {
    this.getEmployeeList()
  },
  methods: {
    // 分配角色
    editRole (row) {
      this.showRoleDialog = true
      // console.log(row)
      this.$refs.roleDialog.getUserDetailById(row.id)
    },
    // 二维码
    async showCode (url) {
      this.dialogVisible = true
      await this.$nextTick()
      qrcode.toCanvas(this.$refs.qr, url)
    },
    // 导出
    async exportData () {
      // 开始导出
      this.downloadLoading = true
      const userMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      // 根据映射关系获取导出的表头
      // 中文key属性的数组
      const header = Object.keys(userMap)
      const enHeader = Object.values(userMap)
      console.log(header, enHeader)
      // 接下来把list员工列表数据转换成二维数据=》[[],[],...]
      console.log(this.list)
      const data = this.transformList(this.list, enHeader)
      console.log(data)
      // 2. 使用Excel导出插件导出数据（核心）
      // import('@/utils/Export2Excel') 按需加载一个js模块（懒加载）
      const excel = await import('@/utils/Export2Excel')
      // console.log(excel)
      excel.export_json_to_excel({
        // 表头 必填
        header, // 导出数据的表头
        // 表头对应的具体数据 必填
        data,
        filename: `elm-list-${Date.now()}`, // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx'// 导出生成的文件类型
      })
      // 3. 导出成功关闭loading
      this.downloadLoading = false
    },
    transformList (list, enHeader) {
      /**
       * 思路：
       * 1. 准备一个空数据存储转换结果
       * 2. 遍历list根据enHeader转换
       * 3. 返回转换结果
       */
      const secodArray = []
      list.forEach(user => {
        const itemArray = []
        for (const key in user) {
          if (enHeader.includes(key)) {
            // 处理聘用关系，正式，非正式
            if (key === 'formOfEmployment') {
              itemArray.push(this.formatForm(user[key]))
            } else {
              itemArray.push(user[key])
            }
          }
        }
        secodArray.push(itemArray)
      })
      return secodArray
    },
    // 聘用状态
    formatForm (type) {
      const map = {}
      EnumTypes.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    async getEmployeeList () {
      const { data } = await getEmployeeList(this.params)
      // console.log(data)
      this.total = data.total
      this.list = data.rows
    },
    // 页数
    currentChange (val) {
      // console.log(val)
      this.params.page = val
      this.getEmployeeList()
    },
    // 每页的个数
    sizeChange (val) {
      console.log(val)
      this.params.size = val
      this.getEmployeeList()
    },
    async hDelEmployee (id) {
      try {
        await this.$confirm('确定要删除吗？', '提示')
        await delEmployee(id)
        const newPage = Math.ceil((this.total - 1) / this.params.size)
        if (newPage > 0) {
          this.params.page = newPage
        }
        // console.log(666)
        // this.params.page = 1
        this.$message.success('删除成功！')
        this.getEmployeeList()
      } catch (error) {
        console.log('取消')
      }
      // console.log(id)
    }

  }
}
</script>
<style lang="scss" scoped>
.round {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
</style>
